package com.ruoyi.web.controller.system;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.vo.TimeParamVo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.domain.WechatMPLoginParams;
import com.ruoyi.framework.web.service.SysLoginService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.entity.YhMember;
import com.ruoyi.system.service.IYhMemberService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2023-06-06
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/yh/member")
public class YhMemberController extends BaseController
{
    @Autowired
    private IYhMemberService yhMemberService;

    @Autowired
    private SysLoginService loginService;

    /**
     * 查询用户列表
     */
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('yh:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(YhMember yhMember)
    {
        startPage();
        List<YhMember> list = yhMemberService.listByAdmin(yhMember);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @ApiOperation("导出用户列表")
    @PreAuthorize("@ss.hasPermi('yh:member:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YhMember yhMember)
    {
        List<YhMember> list = yhMemberService.list(yhMember.queryWrapper());
        ExcelUtil<YhMember> util = new ExcelUtil<YhMember>(YhMember.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取当前登录用户详细信息
     */
    @ApiOperation("获取当前登录用户详细信息")
    @PreAuthorize("@ss.hasPermi('yh:member:list')")
    @GetMapping(value = "/getUserInfo")
    public AjaxResult getUserInfo()
    {
        return success(yhMemberService.getById(SecurityUtils.getUserId()));
    }

    @ApiOperation("根据ID获取用户详情")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('yh:member:list')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(yhMemberService.getById(id));
    }

    @ApiOperation("会员中心（当前登录用户会员信息）")
    @PreAuthorize("@ss.hasPermi('yh:member:list')")
    @GetMapping(value = "/member/level")
    public AjaxResult memberLevel()
    {
        return success(yhMemberService.memberLevel());
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('yh:member:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YhMember yhMember)
    {
        YhMember yhMember1 = new YhMember();
        yhMember1.setId(yhMember.getId());
        yhMember1.setNickName(yhMember.getNickName());
        yhMember1.setFace(yhMember.getFace());
        yhMember1.setMobile(yhMember.getMobile());
        return toAjax(yhMemberService.save(yhMember1));
    }

    /**
     * 用户修改自己的信息
     */
    @ApiOperation("用户修改自己的信息")
    @PreAuthorize("@ss.hasPermi('yh:member:list')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping()
    public AjaxResult edit(@RequestBody YhMember yhMember)
    {
        YhMember yhMember1 = new YhMember();
        yhMember1.setId(SecurityUtils.getUserId().toString());
        yhMember1.setNickName(yhMember.getNickName());
        yhMember1.setFace(yhMember.getFace());
        yhMember1.setMobile(yhMember.getMobile());
        return toAjax(yhMemberService.updateById(yhMember1));
    }

    /**
     * 禁用（启用）用户
     */
    @ApiOperation("禁用（启用）用户")
    @PreAuthorize("@ss.hasPermi('yh:member:disable')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping("/disable")
    public AjaxResult disable(@RequestBody YhMember yhMember)
    {
        YhMember yhMember1 = new YhMember();
        yhMember1.setId(yhMember.getId());
        yhMember1.setIsDisable(yhMember.getIsDisable());
        return toAjax(yhMemberService.updateById(yhMember1));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "ids", value = "用户ID集合", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('yh:member:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        return toAjax(yhMemberService.removeByIds(ids));
    }

    /**
     * 小程序登录
     */
    @ApiOperation("小程序登录")
    @PostMapping("/mp/bind")
    public AjaxResult bind(@RequestBody WechatMPLoginParams params)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.mpBind(params);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取当前登录用户的分享二维码
     */
    @ApiOperation("获取当前登录用户的分享二维码")
    @GetMapping("/getShareQRCode")
    public void getShareQRCode(HttpServletResponse response)
    {
        try {
            yhMemberService.getShareQRCode(response);
        }catch (Exception e){
            throw new ServiceException("获取二维码失败");
        }
    }

    /**
     * 获取当前登录用户的邀请列表
     */
    @ApiOperation("获取当前登录用户的邀请列表")
    @PreAuthorize("@ss.hasPermi('yh:member:list')")
    @PostMapping("/inviteList")
    public TableDataInfo inviteList(@RequestBody TimeParamVo timeParamVo)
    {
        startPage();
        String beginTime = timeParamVo.getBeginTime();
        LambdaQueryWrapper<YhMember> queryWrapper = new LambdaQueryWrapper<YhMember>()
                .eq(YhMember::getParentId, SecurityUtils.getUserId());
        if(StringUtils.isNotEmpty(beginTime)) {
            queryWrapper.ge(YhMember::getCreateTime, beginTime + " 00:00:01")
                    .le(YhMember::getCreateTime, DateUtils.getLastday(beginTime.substring(0, 4), beginTime.substring(5, 7)) + " 23:59:59");
        }
        List<YhMember> list = yhMemberService.list(queryWrapper);
        list.forEach(YhMember::removeSensitive);
        return getDataTable(list);
    }

}
